package org.chen.util;

import org.chen.domain.vo.StatisticVO;

import java.text.DecimalFormat;

public class StatisticsUtil {
    
    private static final DecimalFormat DECIMAL_FORMAT = new DecimalFormat("#.#");

    /**
     * 创建统计数据对象
     *
     * @param title 标题
     * @param currentValue 当前值
     * @param lastValue 上一期值
     * @param type 类型（success/warning/danger）
     * @return 统计数据对象
     */
    public static StatisticVO createStatistic(String title, long currentValue, long lastValue, String type) {
        StatisticVO statistic = new StatisticVO();
        statistic.setTitle(title);
        statistic.setNumber((int) currentValue);
        
        // 计算变化值
        long change = currentValue - lastValue;
        statistic.setChange(formatChange(change));
        
        // 计算变化趋势（百分比）
        double trend = lastValue == 0 ? 0 : (change * 100.0 / lastValue);
        statistic.setTrend(Double.parseDouble(DECIMAL_FORMAT.format(trend)));
        
        statistic.setType(type);
        
        return statistic;
    }

    /**
     * 格式化变化值（添加正负号）
     */
    private static String formatChange(long change) {
        return (change >= 0 ? "+" : "") + change;
    }

    /**
     * 计算环比增长率
     */
    public static double calculateGrowthRate(long current, long previous) {
        if (previous == 0) {
            return 0;
        }
        return (current - previous) * 100.0 / previous;
    }

    /**
     * 判断统计类型
     */
    public static String determineType(double trend) {
        if (trend > 0) {
            return "success";
        } else if (trend < 0) {
            return "danger";
        }
        return "info";
    }
}